#include "Clove_Encoder.h"
ESP32Encoder encoder;

unsigned long Clove_Encoder::update_time = 0; // the private and static variables need to initialize like this. 
unsigned long Clove_Encoder::updateK_time = 0;
int64_t Clove_Encoder::prev_position = 0;
/*! @brief Initialize the Encoder. */
void Clove_Encoder::begin()
{
    encoder.attachHalfQuad(DT, CLK);
    encoder.setCount(0);

}

/*! @brief Write a certain length of data to the specified register address. */

/*! @brief Read a certain length of data to the specified register address. */

/*! @brief Read the encoder value.
    @return The value of the encoder that was read */
signed short int Clove_Encoder::getEncoderValue()
{
    if (update_time + 10 < millis())
    {
        update_time = millis();
        auto pos = encoder.getCount() / 2;
        if (prev_position != pos)
        {
            Serial.printf("Encoder position=%d\n", pos);
            prev_position = pos;
        }
    }

    return prev_position;
}

/*! @brief Get the current status of the rotary encoder keys.
    @return 1 if the set was press, otherwise 0.. */
bool Clove_Encoder::getButtonStatus()
{
    if (updateK_time + 45< millis()) // 40-50  millis has the best effect;
    {
        updateK_time = millis();
        if (button_K=!pcf.digitalRead(4)) //3 is right,2 is left,1 is down,0 is up. 4is the key. 
        {
            Serial.println("Encoder button pressed");
            return button_K; // maybe true or false 
           
        } // needs to place the 4 with pin in the pins_confs.
       
    }
     return false; // in the debounce time 
}

/*! @brief Set the color of the LED (HEX). */
